﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

namespace BerkeleyAlgorithm
{
    class tcpClient
    {
        public TcpClient tcpclnt;

        public tcpClient(IPAddress ip, int port)
        {
            Console.WriteLine("ip: " + ip.ToString() + " port: " + port);
            try
            {
                tcpclnt = new TcpClient();
                Console.WriteLine("connecting...");
                tcpclnt.Connect(ip, port); // use the ipaddress as in the server program
                Console.WriteLine("connected");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
        public void exit()
        {
            tcpclnt.Close();
        }

        public void sendMsg(String msg)
        {
            Console.WriteLine("sending "+msg+" to "+tcpclnt.ToString());
            Stream stm = tcpclnt.GetStream();
            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] word = asen.GetBytes(msg);
            stm.Write(word, 0, word.Length);
            Console.WriteLine("msg sent");
        }

        public string getMsg()
        {
            Console.WriteLine("getting msg");
            string ret;

            ret = "";
            Stream stm = tcpclnt.GetStream();
            byte[] word = new byte[100];
            int k = stm.Read(word, 0, 100);

            for (int i = 0; i < k; i++)
                ret += (Convert.ToChar(word[i]));

            Console.WriteLine("got "+ret);
            return ret;
        }
    }
}
